from StringIO import StringIO
from Products.KnowledgeEngine.Utils.helpers import getMemberPassword

members = context.portal_membership.listMembers()
groups  = context.portal_groups.listGroups()


def quoterow( *values ):
    return '"' + '","'.join( [str(value) for value in values] ) + '"'

propertyIds = context.portal_memberdata.propertyIds() + context.portal_groupdata.propertyIds()



def urlencode( data ):
    out = ""
    for key, value in data.items():
        out += "&%s=%s" % (key, value)
        
    return out

#print '"username","roles","metadata"'
print quoterow( "type", "username", "password", "roles", "groups", *propertyIds )

for group in groups:
    
    data = []
    for property in propertyIds:
        try: data.append( group.getProperty(property) or "" )
        except ValueError: pass
            
    roles = "|".join(group.getRoles())
    groups = "|".join( group.getGroups() )
    
    print quoterow( "group", str(group), "", roles, groups, *data )

for member in members:
    
    data = []
    for property in propertyIds:
        try: data.append( member.getProperty(property) or "" )
        except ValueError: pass
    
    roles = "|".join(member.getRoles())
    groups = "|".join([g.replace("group_","") for g in member.getGroups()])
    
    password = getMemberPassword( member )
    
    print quoterow( "user", member.getId(), password, roles, groups, *data )


    

setHeader = context.REQUEST.RESPONSE.setHeader

setHeader('content-type', 'text/csv')
setHeader('content-disposition','attachment; filename=users.csv')

return printed